import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { finalize, tap } from 'rxjs/operators';
import { environment } from 'environments/environment';
import { AuthInfo } from 'src/app/model/auth-info'
import { User } from 'src/app/model/user';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  readonly tokenStorageKey: string = environment.tokenStorageKey;
  readonly userStorageKey: string = environment.userStorageKey;
  readonly loginUrl: string = environment.loginUrl;
  readonly dashboardUrl: string = environment.dashboardUrl;
  private _redirectUrl: string = this.dashboardUrl;
  readonly emptyUser: User = new User();
  private _user: User;
  constructor(
    private http: HttpClient,
    private router: Router
  ) { }

  login(authInfo: AuthInfo, callback: () => void): void {
    this.http.post(this.loginUrl, authInfo).pipe(
      tap((data: any) => this.setAuthorizationToken(data.token)),
      finalize(callback)
    ).subscribe(
      next => this.router.navigateByUrl(this.dashboardUrl)
    );
  }

  logout(): void {
    this.http.post(environment.logoutUrl, null).pipe(
      finalize(() => {
        this.clearAuthorization();
        this.router.navigateByUrl(this.loginUrl);
      })
    ).subscribe();
  }

  clearAuthorization(): void {
    localStorage.removeItem(this.tokenStorageKey);
    localStorage.removeItem(this.userStorageKey);
  }

  get redirectUrl(): string {
    return this._redirectUrl || this.dashboardUrl;
  }
  set redirectUrl(redirectUrl: string) {
    this._redirectUrl = redirectUrl;
  }
  get isLoggedIn(): boolean {
    return !!this.authorizationToken;
  }

  get authorizationToken(): string {
    return localStorage.getItem(this.tokenStorageKey);
  }
  get user() {
    this._user = this._user || JSON.parse(localStorage.getItem(this.userStorageKey)) || this.emptyUser
    return this._user;
  }
  set user(user: User) {
    localStorage.setItem(this.userStorageKey, JSON.stringify(user));
    this._user = user;
  }
  private setAuthorizationToken(token: string): void {
    localStorage.setItem(this.tokenStorageKey, token);
  }
}
